﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EggController : MonoBehaviour {
    public Animator jumpAnimator;
    public Animator shakeAnimator;
    public GameObject root;
    public GameObject[] eggBodies;

    static List<Animator> _jumps;
    static bool _isDisableJump;

    void Awake() {
        if (_jumps == null) {
            _jumps = new List<Animator>();
            _isDisableJump = false;
        }
    }

    void Start() {
        _jumps.Add(jumpAnimator);
    }

    void OnDestroy() {
        if (_jumps != null) {
            _jumps.Clear();
            _jumps = null;
            _isDisableJump = false;
        }
    }

    public void EnableJump(bool isEnabled) {
        if (_jumps.Count > 2 || _isDisableJump) {
            return;
        }

        jumpAnimator.enabled = isEnabled;
        jumpAnimator.Play("Jump", -1, 0f);
    }

    public void SwitchToShake() {
        DisableAllJump();

        if (_jumps.Count > 2) {
            return;
        }
        
        jumpAnimator.enabled = false;
        shakeAnimator.enabled = true;
    }

	public void OnClicked() {
        foreach (var go in eggBodies) {
            go.SetActive(true);
        }

        root.SetActive(false);
        _jumps.Remove(jumpAnimator);

        if (_jumps.Count > 0) {
            _jumps[0].enabled = true;

            StartCoroutine(TimeUtility.DelayInvoke(2f, () => {
                if (_jumps.Count >= 2) {
                    _jumps[1].enabled = true;
                }
            }));
        }

        _isDisableJump = false;
    }

    public void DisableAllJump() {
        foreach (var jump in _jumps) {
            jump.enabled = false;
        }

        _isDisableJump = true;
    }
}
